$package('common.report');
$import('common.knowledge.knowledgeTree');
$import('common.config.category.CICategoryTreeUtil');
$import('common.security.xssUtil');

/**  
 * @fileOverview "统计项管理"
 * @author Van  
 * @constructor WSTO
 * @description 统计项管理
 * @date 2011-09-13
 * @version 1.0  
 * @since version 1.0 
 */

/**  
 * @author Van  
 * @constructor WSTO
 * @description 自定义报表.
 * @date 2010-11-17
 * @since version 1.0 
 */ 
common.report.customReportGrid=function(){
	
	this.report_scheduldTask_url="scheduledTask!saveScheduledTask.action";
	
	
	return {
		/**
		 * @description 显示报表.
		 * @param cell 当前列值
		 * @param event 事件
		 * @param data 行数据
		 */
		actionFormatter:function(cell,event,data){
			//<a href="javascript:void(0)" onclick="common.report.customReportGrid.preEditParams('+data.reportId+')">'+i18n["custom_report_editParam"]+'</a>&nbsp;&nbsp;
			return '<a href="javascript:common.report.customReportGrid.preView('+data.reportId+',\''+data.reportName+'\',\''+data.reportUrl+'\')">'+i18n["custom_report_previewReport"]+'</a>';
			
		},
		/**
		 * @description 报表格式化.
		 * @param cell 当前列值
		 * @param event 事件
		 * @param data 行数据
		 */
		reportNameFormatter:function(cell,event,data){
			return data.reportName;
		},
		/**
		 * @description 报表格式化.
		 * @param cell 当前列值
		 * @param event 事件
		 * @param data 行数据
		 */
		autoreportModule:function(cell,event,data){
			if(data.reportModule=='itsm_report_leftMenuName_request')
				return i18n['leftMenuName_request'];
			if(data.reportModule=='itsm_report_leftMenuName_problem')
				return i18n['leftMenuName_problem'];
			if(data.reportModule=='itsm_report_leftMenuName_change')
				return i18n['leftMenuName_change'];
			if(data.reportModule=='itsm_report_leftMenuName_CIReport')
				return i18n['leftMenuName_CIReport'];
			if(data.reportModule=='itsm_report_leftMenuName_Retrospect')
				return i18n['leftMenuName_Retrospect'];
			else
				return i18n['leftMenuName_Unknown'];
		},
		/**
		 * @description 报表格式化.
		 * @param cell 当前列值
		 * @param event 事件
		 * @param data 行数据
		 */
		autoSendFormatter:function(cell,event,data){
			var arr={'true':i18n['label_basicConfig_deafultCurrencyYes'],'false':i18n['label_basicConfig_deafultCurrencyNo']};
			return arr[data.autoSend];
		},
		
		/**
		 * 加载列表.
		 */
		showGrid:function(){
			var params = $.extend({},jqGridParams, {
				url:'customReport!findPager.action',
				colNames:[i18n['custom_report_reportName'],i18n['custom_report_reportModule'],i18n['custom_report_automatic'],i18n['custom_report_sendeamil'],i18n['title_creator'],i18n['title_updator'],i18n['common_createTime'],i18n['common_updateTime'],i18n['custom_report_action'],'','','',i18n['custom_report_databaseType'],'',''],
				colModel:[
			   		{name:'reportName',align:'center',width:25,formatter:common.report.customReportGrid.reportNameFormatter},
			   		{name:'reportModule',align:'center',width:25,formatter:common.report.customReportGrid.autoreportModule},
			   		{name:'autoSend_panel',index:'autoSend',align:'center',width:12,formatter:common.report.customReportGrid.autoSendFormatter},
			   		{name:'sendToEmail',align:'center',width:20},
			   		{name:'creator',align:'center',width:30},
			   		{name:'lastUpdater',align:'center',width:30},
			   		{name:'createTime',align:'center',width:25},
			   		{name:'lastUpdateTime',align:'center',width:25},
			   		{name:'action',sortable:false,align:'center',width:30,formatter:common.report.customReportGrid.actionFormatter},
			   		{name:'reportId',hidden:true},
			   		{name:'autoSend',hidden:true},
			   		{name:'reportUrl',hidden:true},
			   		{name:'dbType',hidden:true},
			   		{name:'reportBoolean',hidden:true},
			   		{name:'scheduledTaskId',hidden:true}
			   	],
				jsonReader: $.extend(jqGridJsonReader, {id: "reportId"}),
				sortname:'reportId',
				pager:'#customReportGridPager',
				/*gridComplete:function(){
					
				}*/
			});
			$("#customReportGrid").jqGrid(params);
			$("#customReportGrid").navGrid('#customReportGridPager',navGridParams);
			//列表操作项
			$("#t_customReportGrid").css(jqGridTopStyles);
			$("#t_customReportGrid").html($('#customReportGridToolbar').html());
		},
		
		/**
		 * 添加.
		 */
		preAdd:function(){
			windows('customReport_add_window',{width:460});
			$('#customReport_creator').val(loginName);	//添加创建者
			$('#customReport_lastUpdater').val(loginName);	//添加更新者
			$('#customReport_save').unbind().click(common.report.customReportGrid.add);
			$('#customReportTask_show').unbind().click(common.report.customReportGrid.reportScheduledTask);
			$('#customReport_add_issend').attr("checked",false);
			$('.customReport_add_send_to_email').hide();
		},
		
		
		/**
		 * 上传报表.
		 */
		add:function(){
			$('#base_scheduledTask_beanId').val('autoSendReportByReportJob');
			//var _param = $('#customReport_add_window form').serialize();
			if($('#customReport_addfm').form('validate')){
			startProcess(); 
			$.ajaxFileUpload({
	            url:'customReport!save.action',
	            secureuri:false,
	            fileElementId:'customReport_jrxml_file', 
	            dataType:'json',
	            data:{
					'customReportDTO.reportName':$('#customReport_reportName').val(),
					'customReportDTO.dbType':$('#customReport_dbType').val(),
					'customReportDTO.autoSend':$('#add_customReport_autoSend').val(),
					'customReportDTO.sendToEmail':$('#customReport_add_send_to_email_input').val(),
					'customReportDTO.reportModule':$('#customReport_reportModule').val(),
					'customReportDTO.reportBoolean':$('#add_customReport_boolean').val(),
					'customReportDTO.scheduledTaskId':$('#customReportTask_show_input').val(),
					'customReportDTO.creator':$('#customReport_creator').val(),
					//'customReportDTO.lastUpdater':$('#customReport_lastUpdater').val()
				},
	            success:function(data,status){
					$('#customReport_add_window').dialog('close');
					resetForm('#customReport_add_window form');
					$('#customReportGrid').trigger('reloadGrid');
					common.report.customReportGrid.loadReportLeftMenu();
					endProcess();
	            },
				error:function(){
	            	msgAlert(i18n['ERROR_CUSTOMREPORT_PARAM'],'info');
	            	endProcess();
	            }
	        });
			}
		},
		
		/**
		 * 上传报表选择定 定时任务列表
		 * */
		reportScheduledTask:function(){
			if(basics.ie6.htmlIsNull("#customReportId")){
				var user_url ='scheduledTask!findPageScheduledTaskReportId.action?queryDTO.scheduledTaskId=';
				$('#customReportId').jqGrid('setGridParam',{page:1,url:user_url}).trigger('reportId');
				windows('scheduledTask_show_report',{title:i18n['custom_report_autoSendReport'],width:450,height:400});
			}else{
				var params = $.extend({},jqGridParams, {	
					url:'scheduledTask!findPageScheduledTaskReportId.action?queryDTO.scheduledTaskId=',
					colNames:['ID',i18n['custom_report_task_title'],i18n['custom_report_task_date'],i18n['check']],
					colModel:[
				   		 {name:'scheduledTaskId',align:'center',width:100},
			 	         {name:'title',align:'left',width:110,sortable:false},
			 	         {name:'createTime',align:'center',width:130,formatter:timeFormatter},
			 	         {name:'act', width:80,sortable:false,align:'center',formatter:function(cell,event,data){
								return '<div style="padding:0px">'+
								'<a href="javascript:common.report.customReportGrid.save_Task(\''+(data.scheduledTaskId)+'\',\''+(data.title)+'\')" title="'+i18n['check']+'">'+
								'<img src="../images/icons/ok.png"/></a>'+
								'</div>';	
							}}
				   	],		
					jsonReader: $.extend(jqGridJsonReader, {id: "reportId"}),
					sortname:'reportId',
					pager:'#customReportIdPager',
					multiselect:false,
					ondblClickRow:function(rowId){
						var data=$('#customReportId').getRowData(rowId);
						common.report.customReportGrid.save_Task(data.scheduledTaskId,data.title);
					}
				});
				
				$("#customReportId").jqGrid(params);
				$("#customReportId").navGrid('#customReportIdPager',navGridParams);
				//列表操作项
				$('#customReportId').trigger('reloadGrid');
				windows('scheduledTask_show_report',{width:440,height:400,title:i18n['custom_report_autoSendReport']});
				$("#t_customReportId").hide();
				/*
				$("#t_customReportId").css(jqGridTopStyles);
				$("#t_customReportId").append($('#customReportTaskToolbar').html());*/
			}
		},
		/**
		 * 获取显示任务列表信息
		 * @param id 任务编号
		 * @param title 任务标题
		 * */
		save_Task:function(id,title){
			$('#customReportTask_show_input').attr('value',id);
			$('#customReportTask_edit_show_input').attr('value',id);
			
			$('#customReportTask_show').attr('value',title);
			$('#customReportTaskTitle_edit_show_input').attr('value',title);
			$('#scheduledTask_show_report').dialog('close');
		},
		
		/**
		 *对上传的报表及时更新到相应报表模块
		 * */
		loadReportLeftMenu:function(){
			$.post('customReport!findPager.action',function(data){
				if(data!=null){
					$('#itsm_report_leftMenuName_request').html('');
					$('#itsm_report_leftMenuName_problem').html('');
					$('#itsm_report_leftMenuName_change').html('');
					$('#itsm_report_leftMenuName_CIReport').html('');
					$('#itsm_report_leftMenuName_Retrospect').html('');
					var items = data.data; 
					for(var i=0;i<items.length;i++){
						if(items[i].reportBoolean){
							$('#'+items[i].reportModule).append('<a href=javascript:common.report.customReportGrid.preView(\''+items[i].reportId+'\',\''+items[i].reportName+'\',\''+items[i].reportUrl+'\')>'+items[i].reportName+'</a><br/>');
						}
					}
				}
			})
		},
		
		
		/**
		 * 调用方法保存定时任务.
		 * @param isAuto 布尔值
		 * @param id     编号
		 * @param callback 回调函数 
		 */
		save_report_scheduldTack:function(isAuto,id,callback){			
			$('#base_scheduledTask_reportId').val(id);
			
			if(isAuto=='true'){
				//if($('#scheduledTask_add_form').form('validate')){
					var frm = $('#scheduledTask_add_comm_form,#scheduledTask_add_form').serialize();
					$.post(report_scheduldTask_url,frm, function(res){
						callback();
					});
				//}
			}else{
				callback();
			}
		},
		
		
		
		
		/**
		 * 删除.
		 */
		del:function(){	
			checkBeforeDeleteGrid('#customReportGrid',function(ids){
				var _param=$.param({'reportIds':ids},true);
				$.post('customReport!delete.action',_param,function(){
					msgShow(i18n['custom_report_msg_delete'],'show');
					$('#customReportGrid').trigger('reloadGrid');
					common.report.customReportGrid.loadReportLeftMenu();
				});
			});
		},
		
		
		/**
		 * 编辑.
		 */
		preEdit:function(){	
			$('#base_scheduledTask_id').val('');
			$('#base_scheduledTask_beanId').val('autoSendReportByReportJob');
			checkBeforeEditGrid('#customReportGrid',function(rowData){
				var boo=Boolean(rowData.autoSend);
				if(boo==true){
					
					$('#customReport_edit_issend').attr('checked',boo);
				}

				$('#edit_customReport_lastUpdater').val(loginName);	//添加更新者
				$('#edit_customReport_reportName').val(rowData.reportName);
				$('#edit_customReport_reportId').val(rowData.reportId);
				$('#customReportTask_edit_show_input').val(rowData.scheduledTaskId);
				$('#customReport_edit_sendToEmail').val(rowData.sendToEmail);
				if(rowData.reportModule=='请求模块')
					$('#leftMenuName_request').attr({'selected':'selected'});
				if(rowData.reportModule=='问题模块')
					$('#leftMenuName_problem').attr({'selected':'selected'});
				if(rowData.reportModule=='变更模块')
					$('#leftMenuName_change').attr({'selected':'selected'});
				if(rowData.reportModule=='配置项模块')
					$('#leftMenuName_CIReport').attr({'selected':'selected'});
				if(rowData.reportModule=='用户回访模块')
					$('#leftMenuName_Retrospect').attr({'selected':'selected'});
				if(rowData.reportBoolean=='true')
					$('#customReport_edit_show').attr({"checked":'checked'});
				else
					$('#customReport_edit_hide').attr({'checked':'checked'});
				if(rowData.autoSend=='true'){
					$('#customReport_edit_issend').attr({"checked":true});
					$('#customReport_edit_send_to_email').show();
					$('#edit_customReport_autoSend').val(true);
				}else{
					$('#customReport_edit_issend').attr({"checked":false});
					$('#customReport_edit_send_to_email').hide();
					$('#edit_customReport_autoSend').val(false);
				}
				windows('customReport_edit_window',{width:450,height:265});
				$('#customReport_edit_save').unbind().click(common.report.customReportGrid.doEdit);
				$('#customReportTask_edit_show').unbind().click(common.report.customReportGrid.reportScheduledTask);
				
				report_scheduldTask_url="scheduledTask!editScheduledTask.action";
				
				$('#base_scheduledTask_reportId').val(rowData.reportId);
				
				//查找定时任务
				if(rowData.scheduledTaskId!=null && rowData.scheduledTaskId!=''){
					var _url = 'scheduledTask!findScheduledTaskById.action';
					$.post(_url,'queryDTO.scheduledTaskId='+rowData.scheduledTaskId,function(data){
						if(data.requestDTO!=null)
							$('#customReportTaskTitle_edit_show_input').val(data.requestDTO.etitle);
						//common.tools.scheduledTask.scheduledTasksManage.setScheduledTaskValue(data);
					});
				}
			});
		},
		
		/**
		 * 执行编辑.
		 */
		doEdit:function(){
			
			var _param = $('#customReport_edit_window form').serialize();
			var _url='customReport!merge.action';
			var _reportId=$('#edit_customReport_reportId').val();
			
			if($('#customReport_editfm').form('validate')){
			$.post(_url,_param,function(){
				
				//common.report.customReportGrid.save_report_scheduldTack($('#edit_customReport_autoSend').val(),_reportId,function(){
					
					$('#customReport_edit_window').dialog('close');
					$('#customReportGrid').trigger('reloadGrid');		
					resetForm('#customReport_edit_window form');
					msgShow(i18n['custom_report_msg_edit'],'show');
				    common.report.customReportGrid.loadReportLeftMenu();
				//});
			});
			}
		},
		/**
		 * 参数编辑
		 */
		preEditParams:function(id){
			$.post('customReport!findParamsByReportId.action?reportId='+id,function(res){
				
				$('#param_table tbody').empty();
				
				if(res!=null && res.length>0){
					var htmlCode='<tr>';
					htmlCode+='<td>_paramName</td>';
					htmlCode+='<td><input name="paramsMap[_paramId].paramAlias" value="_paramAlias" /></td>';
					htmlCode+='<td>';
					htmlCode+=$('#paramValueType').html()
					htmlCode+='</td>';
					htmlCode+='<td>';
					htmlCode+=$('#paramDefaultValue').html()
					htmlCode+='</td>';
					
					htmlCode+="</tr>";
					$.each(res,function(k,v){
						var tr=htmlCode
						.replace("_valueSelector_name","paramsMap[_paramId].valueSelector")
						.replace("_selector_id","_selector_"+v.paramId)
						.replace("_defaultValue_name","paramsMap[_paramId].paramDefaultValue")
						.replace("_defaultValue_id","_defaultValue_"+v.paramId)
						
						.replace('_paramName',v.paramName)
						.replace(/_paramId/g,v.paramId)
						.replace('_paramAlias',v.paramAlias)
						.replace('_valueSelector',v.valueSelector);
						$('#param_table tbody').append(tr);
								
						$('#_selector_'+v.paramId).val(v.valueSelector);
						if((v.paramDefaultValue)==null||(v.paramDefaultValue)=="null"){
							v.paramDefaultValue=i18n['leftMenuName_Unknown'];
						}
						
						$('#_defaultValue_'+v.paramId).val(v.paramDefaultValue);
					});
				}
				windows('customReport_edit_param_window',{width:480});
				$('#save_all_params_btn').unbind().click(common.report.customReportGrid.saveAllParams);
			});			
		},
		/**
		 * 保存全部参数
		 * */
		saveAllParams:function(){
			
			var _param = $('#customReport_edit_param_window form').serialize();
			var _url='customReport!mergeAllParams.action';
			$.post(_url,_param,function(){
				
				$('#customReport_edit_param_window').dialog('close');
				resetForm('#customReport_edit_param_window form');
				msgShow(i18n['custom_report_msg_param_edit'],'show');
			});
		},
		
		/**
		 * 获取值选择器.
		 * @param valueSelector 预览报表的值的选项
		 * @param paramName 预览报表的 参数
		 * @param paramId 预览报表的参数编号
		 * @param paramValue 预览报表的 参数值
		 * @param putId 预览报表的 地址ID
		 */
		generateSelectValueHTML:function(valueSelector,paramName,paramId,paramValue,putId){
			var html=$('#'+valueSelector).html().replace("&quot;_paramName&quot;","'"+paramName+"'").replace("&quot;_paramId&quot;","'"+paramId+"'");
			if(valueSelector=='common_date'){
				html = html.replace('common_date','common_date_'+paramId);
			}
			$(putId).html(html);
			$(putId+' input:text,select').val(paramValue);
			
			if(valueSelector=='common_date'){
				DatePicker97(['#common_date_'+paramId]);
			} 
		},
		
		
		/**
		 * 预览报表.
		 * @param reportId 预览报表的编号
		 * @param reportName 预览报表的名称
		 * @param reportUrl 预览报表的地址
		 */
		preView:function(reportId,reportName,reportUrl){
				
				$.post('customReport!findParamsByReportId.action?reportId='+reportId,function(res){
				
				$('#preView_table tbody').empty();
				$('#preView_reportId').val(reportId);
				
				if(res!=null && res.length>0){
					
					var htmlCode='<tr>';
					htmlCode+='<td>_paramAlias</td>';
					htmlCode+='<td>';
					htmlCode+='<div id="valueSelector__paramId"></div>';
					htmlCode+='</td>';
					htmlCode+="</tr>";
					
					$.each(res,function(k,v){
						
						var tr=htmlCode
						.replace(/_paramId/g,v.paramId)
						.replace('_paramAlias',v.paramAlias);
						
						$('#preView_table tbody').append(tr);
						if((v.paramDefaultValue)==null||(v.paramDefaultValue)=="null"){
							v.paramDefaultValue=i18n['leftMenuName_Unknown'];
						}
						common.report.customReportGrid.generateSelectValueHTML(v.valueSelector,v.paramName,v.paramId,v.paramDefaultValue,'#valueSelector_'+v.paramId);
					});
				}
				
				windows('customReport_preview_window',{width:400});
				$.parser.parse($('#preView_table tbody'));
				
				
				$('#report_preview_btn').unbind().click(function(){
					
					common.report.customReportGrid.showReport(reportName,reportUrl);
				});
			});
			
		},

		/**
		 * 显示报表
		 * @param reportName 报表名称
		 * @param reportUrl 报表地址
		 */
		showReport:function(reportName,reportUrl){
			
			var _param = $('#customReport_preview_window form').serialize();
			basics.tab.tabUtils.refreshTab(reportName,'../pages/customReport!showReport.action?fileName='+reportUrl+'&'+_param);
		},
		/**
		 * 打开搜索窗体
		 */
		open_presearch:function(){
			windows('customReport_search_window',{width:460,modal: false});
		},
		/**
		 *搜索事件
		 **/
		doSearch:function(){
			var _url = 'customReport!findPager.action';
			var sdata = $('#customReport_search_window form').getForm();
			var postData = $("#customReportGrid").jqGrid("getGridParam", "postData");     
			$.extend(postData, sdata);
			$('#customReportGrid').jqGrid('setGridParam',{page:1,url:_url}).trigger('reloadGrid');
		},
		
		/**
		 * 载入.
		 */
		init:function(){
			
			//清除重复表单
			clearRelForm(['customReport_add_window','customReport_edit_window','customReport_edit_param_window','scheduledTask_show_report']);
			//绑定日期控件
			DatePicker97(['#newdate']);
			$('.loading,#customReportContent').hide();
			
			$('#customReportContent').show();
			$('#link_customReport_search_ok').click(function(){common.report.customReportGrid.doSearch();});
			setTimeout(function(){
				common.report.customReportGrid.showGrid();
				common.report.customReportGrid.loadReportLeftMenu();
				//$.parser.parse($('#customReports_windows'));
				$('#customReportGrid_add').click(common.report.customReportGrid.preAdd);//添加
				$('#customReportGrid_delete').click(common.report.customReportGrid.del);//删除
				$('#customReportGrid_edit').click(common.report.customReportGrid.preEdit);//编辑
				$('#customReportGrid_search').click(common.report.customReportGrid.open_presearch);//搜索
			},0);
		}
	};
	
}();

$(document).ready(common.report.customReportGrid.init);